// pages/goodsDetail/goodsDetail.js
import goodsApi from '../../service/goodsApi.js'
import { $wuxLoading } from '../../components/wux/index'
import { $wuxDialog } from '../../components/wux/index'
import { reLogin } from '../../service/request'
const app = getApp()
let iptNumberComponent // 数字输入框组件实例
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsInfo: {
      goodsId: "",
      name: "",
      price: "",
      realPrice: "",
      remark: "",
      expressFee: "", // 运费
      commission: "", // 佣金
      goodsType: "1", // 商品类型 1-即买即提 2-商品券
    },
    supplierInfo: { // 供应商信息
      supplierId: "",
      name: "",
      logo: "",
      intro: "",
      address: ""
    },
    picList: [], // banner list
    decImgList: [], // 详情图片
    showBuyPopup: false, // 是否展示购买弹窗
    specList: [], // 所有属性
    selectedList: [], // 已选列表
    goodsInfoList: [], // 可用组合列表
    isTalent: false, // 是否为店主
    isRecommend: false, // 是否为强推商品
    maxStock: '9999',
    btnText: '确认',
    specsBtn: true, // 规格弹窗是否是点击规格按钮 
    noStockClass: false, // 切换按钮缺货状态 class
    spinning: false, // 购买弹窗的 loading
    getAttrFlag: false, // 是否获取过 商品属性
    confirmLoading: false, // 确认按钮的 loading
    hadAuthFlag: false, // 是否授权过用户信息
    showCommissionRules: false, // 返佣规则显示 flag ，店主首次分享显示，缓存判断
    firstShared: false, // 是否分享过一次了， false 首次分享，true 非首次分享
    orderInfo: { // 订单信息
      name: '',
      imageUrl: '',
      price: '',
      goodsId: '',
      quantity: '1',
      selectedTxt: '',
      stock: '9999',
      talentId: '',
      goodsType: ''
    },
    sysWidth: 750, // 设备宽度
    shareFlag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.setData({
      sysWidth: wx.getSystemInfoSync().windowWidth
    })
    console.log(this.route)
    console.log(options)
    that.$wuxLoading = $wuxLoading()
    that.setData({
      ['goodsInfo.goodsId']: options.goodsId
    })
    if (options.talentId) {
      this.setData({
        ['orderInfo.talentId']: options.talentId
      })
    }
    if (options.source === 'share') {
      this.setData({
        shareFlag: true
      })
    }
    that.checkStatus()
    iptNumberComponent = this.selectComponent('#ipt-quantity') // 获取数字输入框实例
  },
  // 登录状态的检查
  checkStatus () {
    let that = this
    // 判断是否有授权，有授权的话从回调调用方法初始化数据
    // 无授权的话直接调用方法初始化数据
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            hadAuthFlag: true
          })
          if (wx.getStorageSync('token')) {
            that.getGoodsDetail()
          } else {
            app.checkStatusCallback = res => {
              that.setData({
                userInfo: res,
                hasUserInfo: true
              })
              that.getGoodsDetail()
            }
          }
        } else {
          that.getGoodsDetail()
        }
      }
    })
  },
  // 获取商品详情
  getGoodsDetail () {
    var that = this
    var params = {
      goodsId: that.data.goodsInfo.goodsId
    }
    if (that.data.orderInfo.talentId) params.talentId = that.data.orderInfo.talentId
    goodsApi.getGoodsDetail(params).then((res) => {
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        let result = res.data.data
        that.setData({
          goodsInfo: {...result.goodsInfo},
          supplierInfo: {...result.supplierInfo},
          picList: [...result.picList],
          decImgList: [...result.decImgList],
          isTalent: result.isTalent,
          isRecommend: result.goodsInfo.isRecommend
        })
      }
    }).catch((res) => {})
  },
  // 前往供应商信息页面
  toSupplierIntro () {
    let that = this
    wx.navigateTo({
      url: `/pages/supplier/supplier?id=${that.data.supplierInfo.supplierId}`
    })
  },
  // 点击立即购买
  handleBuyNow (e) {
    let that = this
    that.setData({
      showBuyPopup: true,
      specsBtn: e.currentTarget.dataset.specs
    })
    if (!that.data.getAttrFlag) {
      that.setData({
        ['orderInfo.price']: that.data.goodsInfo.realPrice
      })
      that.getGoodsAttr()
    }
  },
  // 关闭立即购买弹窗
  closeBuyPopup () {
    this.setData({
      showBuyPopup: false
    })
  },
  // 获取商品属性
  getGoodsAttr () {
    let that = this
    that.setData({
      spinning: true
    })
    goodsApi.getGoodsAttr({
      goodsId: that.data.goodsInfo.goodsId
    }).then((res) => {
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        // 对获取到的数据添加 selected 属性
        let { specList } = res.data.data
        let picUrl = ''
        specList.forEach((value, i) => {
          value.detailList.forEach((item, j) => {
            if (i === 0 && j === 0) { // 默认选中第一行的第一个
              picUrl = item.picUrl
              item.selected = true
            } else {
              item.selected = false
            }
          })
        })
        that.setData({
          getAttrFlag: true,
          spinning: false,
          specList: [...specList],
          goodsInfoList: [...res.data.data.goodsInfoList],
          ['orderInfo.buyNowImg']: picUrl
        })
        that.initSelectedList()
      } else {
        that.setData({
          getAttrFlag: false,
          spinning: false,
        })
      }
    }).catch((res) => {
      that.setData({
        getAttrFlag: false,
        spinning: false
      })
    })
  },
  // 初始化 selectedList 
  initSelectedList () {
    let that = this
    let obj = { id: '#' }
    for (let i = 0; i < that.data.specList.length; i++) {
      if (i === 0) { // 默认选中第一行的第一个
        let id = that.data.specList[0].detailList[0].id
        let txt = that.data.specList[0].detailList[0].value
        that.data.selectedList.push({id, txt})
      } else {
        that.data.selectedList.push({...obj})
      }
    }
    that.generateSelectedText() // 拼接已选字符串
    that.checkStock() // 检查库存
  },
  // 选择商品属性
  handleSelected (e) {
    let that = this
    let index = e.target.dataset.index
    let id = e.detail.id
    let txt = e.detail.txt
    if (index === 0) {
      that.setData({
        ['orderInfo.buyNowImg']: e.detail.picUrl
      })
    }
    that.setData({
      [`selectedList[` + index + `].id`]: id,
      [`selectedList[` + index + `].txt`]: txt
    })
    that.generateSelectedText()
    that.checkStock()
  },
  // 生成已选择属性的文本字符串
  generateSelectedText () {
    let that = this
    let str = '已选'
    that.data.selectedList.forEach((value, index) => {
      if (value.txt) {
        if (index === (that.data.selectedList.length -1)) {
          str = str + value.txt
        } else {
          str = str + value.txt + "，"
        }
      }
    })
    that.setData({
      ['orderInfo.selectedTxt']: str
    })
  },
  // 生成已选属性的字符串 类似 1-2 
  generateSelectedCombination () {
    let that = this
    if (that.data.selectedList.length === 0) {
      return ''
    } else {
      let tempList = [...that.data.selectedList]
      console.log(tempList)
      let checkStr = ''
      tempList.forEach((value, index) => {
        if (index !== (tempList.length - 1)) {
          checkStr = checkStr + value.id + '-'
        } else {
          checkStr += value.id
        }
      })
      return checkStr
    }
  },
  // 判断库存是否可以购买
  checkStock () {
    let that = this
    let checkStr = that.generateSelectedCombination()
    if (checkStr === '') return false
    console.log(checkStr)
    // 如果还有 “#” 说明还有属性未选择
    if (checkStr.split('-').indexOf('#') !== -1) return false
    // 从可用组合列表中筛选符合条件的元素
    let checkResultArr = that.data.goodsInfoList.filter((value) => value.combination === checkStr)
    if (checkResultArr.length > 0) { // 有符合条件的
      let goodsInfo = {...checkResultArr[0]}
      if (goodsInfo.stock > 0) {
        // 有这个货，也有库存
        console.log(goodsInfo)
        this.setData({
          btnText: '确认',
          noStockClass: false,
          name: goodsInfo.name,
          maxStock: goodsInfo.stock // 将数字输入框允许的最大值设置为当前商品的库存量
        })
        console.log('可购买')
        console.log('当前商品库存为： ', goodsInfo.stock)
        // 若当前输入的大于库存量，设置为库存量
        if (that.data.orderInfo.quantity > goodsInfo.stock) {
          that.setData({
            ['orderInfo.quantity']: goodsInfo.stock
          })
        }
        // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
        iptNumberComponent.updated(that.data.orderInfo.quantity)
        // 填入数据
        that.setData({
          ['orderInfo.imageUrl']: goodsInfo.picUrl,
          ['orderInfo.goodsId']: goodsInfo.goodsId,
          ['orderInfo.price']: goodsInfo.price,
          ['orderInfo.name']: goodsInfo.name,
          ['orderInfo.stock']: goodsInfo.stock,
          ['orderInfo.expressFee']: that.data.goodsInfo.expressFee,
          ['orderInfo.goodsType']: that.data.goodsInfo.goodsType,
        })
        return true
      } else { // 有这个货，但是库存没了的
        // 库存为零的，填入数据，为了保证切换时价格等会变化
        that.setData({
          ['orderInfo.imageUrl']: goodsInfo.picUrl,
          ['orderInfo.goodsId']: goodsInfo.goodsId,
          ['orderInfo.price']: goodsInfo.price,
          ['orderInfo.name']: goodsInfo.name,
          ['orderInfo.stock']: goodsInfo.stock,
          ['orderInfo.expressFee']: that.data.goodsInfo.expressFee,
          ['orderInfo.goodsType']: that.data.goodsInfo.goodsType,
          maxStock: '9999',
          btnText: '缺货',
          noStockClass: true
        })
        // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
        iptNumberComponent.updated(that.data.orderInfo.quantity)
        console.log('不可购买')
        return false
      }
    } else { // 无符合条件的，即 “无货” 的 （就没这个货）    
      that.setData({
        maxStock: '9999',
        btnText: '缺货',
        noStockClass: true
      })
      // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
      iptNumberComponent.updated(that.data.orderInfo.quantity)
      console.log('不可购买')
      return false
    }
  },
  // 购买数量变化
  handleQuantityChange (e) {
    let that = this
    that.setData({
      ['orderInfo.quantity']: e.detail.value
    })
  },
  // 处理加号禁用时的点击
  handleDisableAdd () {
    if ((this.data.orderInfo.quantity - 0) === 9999) {
      wx.showToast({title: '最多购买 9999 个', icon: 'none'})
    } else {
      wx.showToast({title: '库存不足', icon: 'none'})
    }
  },
  // 超过最大值自动修改
  handleDisableMax () {
    // if ((this.data.orderInfo.quantity - 0) === 9999) {
    //   wx.showToast({title: '最多购买 9999 个', icon: 'none'})
    // } else {
    //   wx.showToast({title: '库存不足', icon: 'none'})
    // }
  },
  /**
   * 检测哪些没选
   * 检测生成的 id 组合字符串中是否有 # ，有的话获取下标
   */
  checkSelect () {
    let that = this
    let checkStr = that.generateSelectedCombination()
    let resIndex = checkStr.split('-').indexOf('#')
    if (resIndex !== -1) {
      wx.showToast({
        title: '请选择' + that.data.specList[resIndex].title,
        icon: 'none',
        duration: 1500
      })
      return false
    }
    return true
  },
  // 点击 【确认】 按钮
  handleConfirmBuy () {
    let that = this
    if (that.data.btnText !== '缺货') {
      that.showConfrimLoading()
    }

    if (that.data.hadAuthFlag) {
      console.log('授权过')
      // 检测选择、库存和数量
      if (!that.checkSelect() || !that.checkStock() || (that.data.orderInfo.quantity <= 0)) {
        that.hideConfrimLoading()
        return
      }
      that.hideConfrimLoading()
      app.globalData.orderInfo = {...that.data.orderInfo}
      if (that.data.specsBtn) {
        that.setData({
          showBuyPopup: false
        })
      } else {
        wx.navigateTo({
          url: `/pages/confirmOrder/confirmOrder`
        })
      }
    }
  },
  // 授权回调
  bindGetUserInfo (e) {
    let that = this
    that.showConfrimLoading()
    console.log(e.detail.userInfo)
    if (!!e.detail.userInfo) { // 同意授权-并登陆
      wx.setStorageSync('hadAuthFlag', true)
      app.globalData.userInfo = e.detail.userInfo
      app.globalData.hadAuthUserInfo = true
      reLogin().then(() => {
        that.hideConfrimLoading()
        that.setData({
          hadAuthFlag: true
        })
        that.handleConfirmBuy()
        console.log(app.globalData.userInfo)
      }).catch((res) => {
        that.hideConfrimLoading()
      })
    } else { // 不同意授权
      that.hideConfrimLoading()
      wx.setStorageSync('hadAuthFlag', false)
      that.setData({
        hadAuthFlag: false
      })
    }
  },
  openConfirmModel () {
    let that = this
    $wuxDialog().confirm({
      resetOnClose: true,
      closable: false,
      maskClosable: true,
      title: '设置强推',
      content: '确认将该商品设置为“店主强推”？',
      confirmText: '确认',
      cancelText: '取消',
      onConfirm() {
        that.handleAddRecommend()
      }
    })
  },
  // 处理上强推操作
  handleAddRecommend () {
    let that = this
    goodsApi.addRecommend({
      goodsId: that.data.goodsInfo.goodsId
    }).then((res) => {
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        wx.showToast({
          title: '操作成功',
          icon: 'none',
          duration: 1500
        })
        app.globalData.refreshIndexFlag = true
        wx.switchTab({
          url: '/pages/index/index'
        })
      }
    }).catch((res) => {})
  },
  // 显示 确定 按钮的 loading
  showConfrimLoading () {
    this.setData({
      confirmLoading: true
    })
  },
  // 隐藏 确定 按钮的 loading
  hideConfrimLoading () {
    this.setData({
      confirmLoading: false
    })
  },
  // 关闭佣金规则
  closeCommissionRules () {
    this.setData({
      showCommissionRules: false,
      firstShared: true
    })
    wx.setStorageSync('firstShared', true)
  },
  // 首次分享
  handleFirstShare () {
    this.setData({
      showCommissionRules: true
    })
  },
  // 返回首页
  toIndex () {
    let url = '/pages/index/index'
    url = this.data.orderInfo.talentId ? url + '?talentId=' + this.data.orderInfo.talentId : url
    console.log('url --- ' + url)
    app.globalData.refreshIndexFlag = true
    wx.reLaunch({
      url
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let firstShared = wx.getStorageSync('firstShared')
    this.setData({
      firstShared
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.$wuxLoading.hide()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.$wuxLoading.hide()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this
    var imageUrl = that.data.picList.length > 0 ? that.data.picList[0] : '/resources/images/goodsDetail/banner-default.png'
    let pathParam = that.data.orderInfo.talentId ? '&talentId=' + that.data.orderInfo.talentId : ''
    return {
      title: that.data.goodsInfo.name,
      path: '/pages/goodsDetail/goodsDetail?source=share&goodsId=' + that.data.goodsInfo.goodsId + pathParam,
      imageUrl
    }
  }
})